import {
  getNotifyTemplateInfoByPage,
  addNotifyTemplateInfo,
  updateNotifyTemplateInfo,
  delNotifyTemplateInfo,
  exportNotifyTemplateInfo,
  readOneOrManyOrAllNotify,
  viewBaseInfo,
  getNotifyInfoTotalByPage,
  delNotifyTemplateInfos,
  readAllNotify,
} from '@/services/platform/notifyTemplateInfo';
import { history } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import '@/pages/platform/platform.module.less';
import { Ellipsis } from '@/components/Ellipsis';
import type { tabType } from '../platform/components/interfaceProduct';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Tabs, Row, Col } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
const NotifyTemplateInfo: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const actionRef2 = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);

  const [idlist1, setlidlist1] = useState([]); //通知的已读状态id
  const [idlist_1, setlidlist_1] = useState([]); //通知的未读状态id
  const [idlist2, setlidlist2] = useState([]); //待办的已读状态id
  const [idlist_2, setlidlist_2] = useState([]); //待办的未读状态id
  const [theselectedRowKeys, settheSelectedRowKeys] = useState<React.Key[]>([]);
  const [handlenumber, sethandlenumber] = useState(''); //待办数量

  //选中selection中的序号
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    settheSelectedRowKeys(newSelectedRowKeys);
    console.log('已选择', newSelectedRowKeys);
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
      // search:false,
      // sorter:true,
      align: 'center',
      sorter: true,
    },
    {
      title: '状态',
      dataIndex: 'status',

      valueType: 'select',
      request: async () => [
        { label: '已读', value: 1 },
        { label: '未读', value: -1 },
      ],
      defaultSortOrder: 'ascend', //默认升序，降序用descend
      align: 'center',
      sorter: true,
      width: 100,
      render: (text, record, _, action) => {
        return (
          <div>
            {record.status == 1
              ? '已读'
              : record.status == -1
              ? '未读'
              : record.status == -2
              ? '未处理'
              : '已处理'}
          </div>
        );
      },
    },
    {
      title: '模块',
      dataIndex: 'moduleName',
      align: 'center',
      sorter: true,
      search: false,
      width: 200,
      render: (text, record, _, action) => {
        return <div>{record.moduleName + '-' + record.funcName}</div>;
      },
    },
    // {
    //   title: '功能',
    //   dataIndex: 'funcName',
    //  align: 'center',sorter: true,
    // },
    {
      title: '内容详情',
      dataIndex: 'notifyDesc',
      // search: false,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 400,
    },
    {
      title: '发送人名称',
      dataIndex: 'senderName',
      search: false,

      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '发送时间',
      dataIndex: 'sendTime',
      search: false,

      align: 'center',
      sorter: true,
      width: 160,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('查看');
            form.setFieldsValue({
              module: record.moduleName + '-' + record.funcName,
              notifyDesc: record.notifyDesc,
              notifyType: record.notifyType,
              receiverName: record.receiverName,
              senderName: record.senderName,
              sendTime: record.sendTime,
              status:
                record.status == 1
                  ? '已读'
                  : record.status == -1
                  ? '未读'
                  : record.status == -2
                  ? '未处理'
                  : '已处理',
            });
          }}
        >
          查看
        </a>,
        // <a
        //   key="dealwithKey"
        //   onClick={async () => {
        //     if (record.status == 1) {
        //       message.warning('当前消息是已读状态');
        //     } else if (record.status == 2) {
        //       message.warning('当前消息是已处理状态');
        //     } else {
        //       const getuserlist = await viewBaseInfo(null);
        //       const para = {
        //         notifyTemplateInfoIdList: [record.notifyTemplateInfoId],
        //         notifyType: record.notifyType,
        //         status: record.status,
        //         userName: getuserlist.data.name,
        //       };
        //       const result = await readOneOrManyOrAllNotify(para);
        //       if (result != null) {
        //         message.success('处理成功');
        //       }
        //       actionRef.current!.reload();
        //       actionRef2.current!.reload();
        //     }
        //   }}
        // >
        //   {record.notifyType == '通知' ? '已读' : '处理'}
        // </a>,
        // <a
        //   key="deleteKey"
        //   onClick={() => {
        //     Modal.confirm({
        //       title: '删除',
        //       content: '确定要删除吗',
        //       okText: '确认',
        //       cancelText: '取消',
        //       onOk: async () => {
        //         await delNotifyTemplateInfo({ notifyTemplateInfoId: record.notifyTemplateInfoId });
        //         actionRef.current!.reload();
        //         actionRef2.current!.reload();
        //       },
        //     });
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];

  const columns2: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
      // search:false,
      // sorter:true,
      align: 'center',
      sorter: true,
    },
    {
      title: '状态',
      dataIndex: 'status',

      valueType: 'select',
      request: async () => [
        { label: '已处理', value: 2 },
        { label: '未处理', value: -2 },
      ],
      defaultSortOrder: 'ascend', //默认升序，降序用descend
      align: 'center',
      sorter: true,
      width: 100,
      render: (text, record, _, action) => {
        return (
          <div>
            {record.status == 1
              ? '已读'
              : record.status == -1
              ? '未读'
              : record.status == -2
              ? '未处理'
              : '已处理'}
          </div>
        );
      },
    },
    {
      title: '模块',
      dataIndex: 'moduleName',
      align: 'center',
      sorter: true,
      width: 200,
      search: false,
      render: (text, record, _, action) => {
        return <div>{record.moduleName + '-' + record.funcName}</div>;
      },
    },
    // {
    //   title: '功能',
    //   dataIndex: 'funcName',
    //  align: 'center',sorter: true,
    // },
    {
      title: '内容详情',
      dataIndex: 'notifyDesc',
      // search: false,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 400,
    },
    {
      title: '发送人名称',
      dataIndex: 'senderName',
      search: false,

      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '发送时间',
      dataIndex: 'sendTime',
      search: false,

      align: 'center',
      sorter: true,
      width: 160,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('查看');
            form.setFieldsValue({
              module: record.moduleName + '-' + record.funcName,
              notifyDesc: record.notifyDesc,
              notifyType: record.notifyType,
              receiverName: record.receiverName,
              senderName: record.senderName,
              sendTime: record.sendTime,
              status:
                record.status == 1
                  ? '已读'
                  : record.status == -1
                  ? '未读'
                  : record.status == -2
                  ? '未处理'
                  : '已处理',
            });
          }}
        >
          查看
        </a>,
      ],
    },
  ];

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '通知',
      content: (
        <div>
          <ProTable
            headerTitle="通知查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="notifyTemplateInfoId" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="clear_1"
                // icon={<PlusOutlined />}
                onClick={async () => {
                  const getuserlist = await viewBaseInfo(null);
                  const result = await delNotifyTemplateInfos({
                    status: 1,
                    userName: getuserlist.data.name,
                  });
                  if (result != null) {
                    message.success('清除成功');
                  }
                  actionRef.current!.reload();
                }}
                type="primary"
              >
                清空已读
              </Button>,
              <Button
                key="dealwith_1"
                // icon={<PlusOutlined />}
                onClick={async () => {
                  if (theselectedRowKeys.length != 0) {
                    const getuserlist = await viewBaseInfo(null);
                    const para = {
                      notifyTemplateInfoIdList: theselectedRowKeys,
                      notifyType: '通知',
                      status: -1,
                      userName: getuserlist.data.name,
                    };
                    const result = await readOneOrManyOrAllNotify(para);
                    if (result != null) {
                      message.success('已读成功');
                    }
                    actionRef.current!.reload();
                    actionRef.current.clearSelected();
                  } else {
                    message.info('请选择要处理的消息！');
                  }
                }}
                type="primary"
              >
                批量已读
              </Button>,
              <Button
                key="dealwith_all_1"
                // icon={<PlusOutlined />}
                onClick={async () => {
                  const getuserlist = await viewBaseInfo(null);
                  const para = {
                    notifyType: '通知',
                    status: -1,
                    userName: getuserlist.data.name,
                  };
                  const result = await readAllNotify(para);
                  if (result != null) {
                    message.success('已读成功');
                  }
                  actionRef.current!.reload();
                }}
                type="primary"
              >
                一键已读
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const getuserlist = await viewBaseInfo(null);
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const para_message = {
                notifyDesc: '',
                status: '',
                notifyType: '通知',
                pageNum: 1,
                pageSize: 20,
                sortField: 'status',
                desc: false,
                userName: getuserlist.data.name,
              };
              // 设置当前页
              para_message.pageSize = params.pageSize;
              para_message.pageNum = params.current;
              // 筛选
              filters.map((item: any) => {
                if (item.field == 'notifyDesc') {
                  para_message.notifyDesc = item.value;
                } else if (item.field == 'status') {
                  para_message.status = item.value;
                }
              });
              // 排序
              sorters.map((item: any) => {
                if (item.field == 'senderName') {
                  para_message.sortField = item.field;
                  para_message.desc = item.desc;
                } else if (item.field == 'status') {
                  para_message.sortField = item.field;
                  para_message.desc = item.desc;
                } else if (item.field == 'sendTime') {
                  para_message.sortField = item.field;
                  para_message.desc = item.desc;
                }
              });
              // result:当前页面结果，result_nofilter：当前页面数据数量
              const [result, result_nofilter] = await Promise.all([
                getNotifyInfoTotalByPage(para_message),
                getNotifyInfoTotalByPage({
                  notifyDesc: '',
                  status: '',
                  notifyType: '待办',
                  pageNum: 1,
                  pageSize: 20,
                  sortField: 'status',
                  desc: false,
                  userName: getuserlist.data.name,
                }),
              ]);
              sethandlenumber(result_nofilter.data.totalElements);
              // console.log(props.location.query.tab_state, 'tab状态');
              // console.log(result.data.content,'通知页面');
              // 保存idlist
              // const list1: any = [];
              // const list_1: any = [];
              // result.data.content.map((item: any) => {
              //   if (item.status == -1) {
              //     list_1.push(item.notifyTemplateInfoId);
              //   } else {
              //     list1.push(item.notifyTemplateInfoId);
              //   }
              // });
              // setlidlist1(list1); //已读
              // setlidlist_1(list_1); //未读
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 1200, y: 350 }}
            rowSelection={{ onChange: onSelectChange }}
          />
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '待办',
      content: (
        <div>
          <ProTable
            headerTitle="待办查询"
            actionRef={actionRef2} //用于触发刷新操作等，看api
            rowKey="notifyTemplateInfoId" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="clear_2"
                // icon={<PlusOutlined />}
                onClick={async () => {
                  const getuserlist = await viewBaseInfo(null);
                  const result = await delNotifyTemplateInfos({
                    status: 2,
                    userName: getuserlist.data.name,
                  });
                  if (result != null) {
                    message.success('清除成功');
                  }
                  actionRef2.current!.reload();
                }}
                type="primary"
              >
                清空已办
              </Button>,
              <Button
                key="dealwith_2"
                // icon={<PlusOutlined />}
                onClick={async () => {
                  if (theselectedRowKeys.length != 0) {
                    const getuserlist = await viewBaseInfo(null);
                    const para = {
                      notifyTemplateInfoIdList: theselectedRowKeys,
                      notifyType: '待办',
                      status: -2,
                      userName: getuserlist.data.name,
                    };
                    const result = await readOneOrManyOrAllNotify(para);
                    if (result != null) {
                      message.success('处理成功');
                    }
                    actionRef2.current!.reload();
                    actionRef2.current.clearSelected();
                  } else {
                    message.info('请选择要处理的消息！');
                  }
                }}
                type="primary"
              >
                批量已办
              </Button>,
              <Button
                key="dealwith_all_2"
                // icon={<PlusOutlined />}
                onClick={async () => {
                  const getuserlist = await viewBaseInfo(null);
                  const para = {
                    notifyType: '待办',
                    status: -2,
                    userName: getuserlist.data.name,
                  };
                  const result = await readAllNotify(para);
                  if (result != null) {
                    message.success('处理成功');
                  }
                  actionRef2.current!.reload();
                }}
                type="primary"
              >
                一键已办
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const getuserlist = await viewBaseInfo(null);
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const para_message = {
                notifyDesc: '',
                status: '',
                notifyType: '待办',
                pageNum: 1,
                pageSize: 20,
                sortField: 'status',
                desc: false,
                userName: getuserlist.data.name,
              };
              // 设置当前页
              para_message.pageSize = params.pageSize;
              para_message.pageNum = params.current;
              // 筛选
              filters.map((item: any) => {
                if (item.field == 'notifyDesc') {
                  para_message.notifyDesc = item.value;
                } else if (item.field == 'status') {
                  para_message.status = item.value;
                }
              });
              // 排序
              sorters.map((item: any) => {
                if (item.field == 'senderName') {
                  para_message.sortField = item.field;
                  para_message.desc = item.desc;
                } else if (item.field == 'status') {
                  para_message.sortField = item.field;
                  para_message.desc = item.desc;
                } else if (item.field == 'sendTime') {
                  para_message.sortField = item.field;
                  para_message.desc = item.desc;
                }
              });
              // result:当前页面结果，result_nofilter：当前页面数据数量
              const [result, result_nofilter] = await Promise.all([
                getNotifyInfoTotalByPage(para_message),
                getNotifyInfoTotalByPage({
                  notifyDesc: '',
                  status: '',
                  notifyType: '待办',
                  pageNum: 1,
                  pageSize: 20,
                  sortField: 'status',
                  desc: false,
                  userName: getuserlist.data.name,
                }),
              ]);
              sethandlenumber(result_nofilter.data.totalElements);
              // const result = await getNotifyInfoTotalByPage({
              //   notifyType: '待办',
              //   pageEntity: {
              //     ...params,
              //     sorters: sorters,
              //     filters: filters,
              //   },
              //   userName: getuserlist.data.name,
              // });
              // console.log(props.location.query.tab_state, 'tab状态');
              // console.log(result.data.content,'待办页面');
              // 保存idlist
              // const list2: any = [];
              // const list_2: any = [];
              // result.data.content.map((item: any) => {
              //   if (item.status == -2) {
              //     list_2.push(item.notifyTemplateInfoId);
              //   } else {
              //     list2.push(item.notifyTemplateInfoId);
              //   }
              // });
              // setlidlist2(list2); //已读
              // setlidlist_2(list_2); //未读
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns2}
            scroll={{ x: 1200, y: 350 }}
            rowSelection={{ onChange: onSelectChange }}
          />
        </div>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        type="card"
        defaultActiveKey={props.location.query.tab_state == 'event' ? '2' : '1'}
        // onTabClick= {()=>{
        //   actionRef.current!.reload();
        //   actionRef2.current!.reload();
        // }}
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label:
              i == 0 ? (
                <div>{item.label}</div>
              ) : (
                <div className="text">
                  {item.label}
                  <div className="point">
                    <div className="number">{handlenumber}</div>
                  </div>
                </div>
              ),
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onCancel={() => setModalVisit(false)}
        footer={[
          <Button key="back" onClick={() => setModalVisit(false)}>
            关闭
          </Button>,
        ]}
        confirmLoading={confirmLoading}
        width={900}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="module"
                label="模块"
                rules={[{ required: true, message: '请输入工单编号!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="notifyType"
                label="类别"
                rules={[{ required: true, message: '请输入工单编号!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item
                name="notifyDesc"
                label="消息内容"
                // hidden={true}
                rules={[{ required: true, message: '请输入工序编号!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="senderName"
                label="发送人"
                // hidden={true}
                rules={[{ required: true, message: '请输入加工顺序编号!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="receiverName"
                label="接收人"
                rules={[{ required: true, message: '请输入任务结束时间!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="sendTime"
                label="发送时间"
                rules={[{ required: true, message: '请输入标准工时!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请输入填报工时!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default NotifyTemplateInfo;
